package com.zfzs.post.sms;

import com.zfzs.post.http.HttpClientUtil;
import com.zfzs.post.qcloudsms.SmsSingleSender;
import com.zfzs.post.qcloudsms.SmsSingleSenderResult;
import com.zfzs.post.utils.JsonUtils;
import com.zfzs.post.qcloudsms.SmsSingleSenderResult;
import com.zfzs.post.utils.JsonUtils;
import com.zfzs.post.http.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * 功能描述:  短信公共类
 *
 * @auther: ck
 * @date: 2018/8/31 14:53
 */
public class SendSms {

    private static final String SING_NAME = "信付助手";

	private static final String APP_ID = "856420";

    private static final String APP_KEY = "2cdbf352e24f324f7256feeed392bf9c";

	private static Logger logger = LoggerFactory.getLogger(SendSms.class);

	/**
	 *  功能描述:  发送阿里短信
	 * @param phone 手机号码
	 * @param smsCode 验证码
	 * @param teCode  短信模板编号
	 * @return
	 * @throws Exception
	 */
	public static Map<String,Object> SendALiSms(String phone , String smsCode,String teCode,String accessKeyId,String accessSecret,String signName) throws Exception {
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("success", false);
   	    resMap.put("message", "短信发送失败！");
		java.text.SimpleDateFormat df = new java.text.SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'");
		// 这里一定要设置GMT时区
		df.setTimeZone(new java.util.SimpleTimeZone(0, "GMT"));
		Map<String, String> paras = new HashMap<String, String>();
		// 1. 系统参数
		paras.put("SignatureMethod", "HMAC-SHA1");
		paras.put("SignatureNonce", java.util.UUID.randomUUID().toString());
		paras.put("AccessKeyId", accessKeyId);
		paras.put("SignatureVersion", "1.0");
		paras.put("Timestamp", df.format(new java.util.Date()));
		paras.put("Format", "JSON");
		// 2. 业务API参数
		paras.put("Action", "SendSms");
		paras.put("Version", "2017-05-25");
		paras.put("RegionId", "cn-hangzhou");
		paras.put("PhoneNumbers", phone);
		paras.put("SignName",signName);
		String TemplateParam = "{\"number\":\"smsCode\"}";
		paras.put("TemplateParam", TemplateParam.replace("smsCode", smsCode));
		paras.put("TemplateCode", teCode);
		paras.put("OutId", "7789");
		// 3. 去除签名关键字Key
		if (paras.containsKey("Signature"))
			paras.remove("Signature");
		// 4. 参数KEY排序
		java.util.TreeMap<String, String> sortParas = new java.util.TreeMap<String, String>();
		sortParas.putAll(paras);
		// 5. 构造待签名的字符串
		java.util.Iterator<String> it = sortParas.keySet().iterator();
		StringBuilder sortQueryStringTmp = new StringBuilder();
		while (it.hasNext()) {
			String key = it.next();
			sortQueryStringTmp.append("&").append(specialUrlEncode(key)).append("=")
					.append(specialUrlEncode(paras.get(key)));
		}
		String sortedQueryString = sortQueryStringTmp.substring(1);// 去除第一个多余的&符号
		StringBuilder stringToSign = new StringBuilder();
		stringToSign.append("GET").append("&");
		stringToSign.append(specialUrlEncode("/")).append("&");
		stringToSign.append(specialUrlEncode(sortedQueryString));
		String sign = sign(accessSecret + "&", stringToSign.toString());
		// 6. 签名最后也要做特殊URL编码
		String signature = specialUrlEncode(sign);
		// 最终打印出合法GET请求的URL
		try {
			 String body = HttpClientUtil.doGet("http://dysmsapi.aliyuncs.com/","Signature="+ signature + sortQueryStringTmp);
			 if(body==null || "".equals(body) || "exception".equals(body)){
				 resMap.put("success", false);
		    	 resMap.put("message", "调用接口失败！");
			 }else{
				 Map<String, Object> map = JsonUtils.fromJson(body.toString());
				 System.out.println(map.toString());
				 if("OK".equals((String)map.get("Code"))){
					 resMap.put("success", true);
			    	 resMap.put("message", "短信发送成功，请注意查收！");
				 }else{
					 resMap.put("success", false);
			    	 resMap.put("message", "短信发送失败！");
				 }
			 }
			
		} catch (Exception e) {
			resMap.put("success", false);
	    	resMap.put("message", "调用接口失败！");
		}
		return resMap;
		
	}

	public static String specialUrlEncode(String value) throws Exception {
		return URLEncoder.encode(value, "UTF-8").replace("+", "%20").replace("*", "%2A").replace("%7E", "~");
	}

	/**
	 *  发送腾讯云短信
	 * @param phone 手机号码
	 * @param smsCode 短信code
	 * @param teCode 短信模板code
	 * @return
	 */
	public static Map<String,Object> SendTengXunSms(String phone , String smsCode,String teCode,String appId,String appKey) {
		Map<String, Object> resMap = new HashMap<String, Object>();
		resMap.put("success", false);
		resMap.put("message", "短信发送失败！");
		//Integer APP_ID = 1400101821;
		//String APP_KEY = "ebe2948c2e23da33a7309a3a683a6c4b";
		ArrayList<String> params = new ArrayList<>();
		params.add(0,smsCode);
		// 最终打印出合法GET请求的URL
		try {
			// 初始化单发
			SmsSingleSender singleSender = new SmsSingleSender(Integer.valueOf(appId), appKey);
			SmsSingleSenderResult singleSenderResult = singleSender.sendWithParam("86", phone, Integer.valueOf(teCode), params, "", "", "");
			System.out.print(singleSenderResult);
			if (singleSenderResult.result == 0) {
				resMap.put("success", true);
				resMap.put("message", "短信发送成功，请注意查收！");
			}else{
				resMap.put("success", false);
				resMap.put("message", "调用接口失败！");
			}
		} catch (Exception e) {
			resMap.put("success", false);
			resMap.put("message", "调用接口失败！");
		}
		return resMap;

	}

	public static String sign(String accessSecret, String stringToSign) throws Exception {
		javax.crypto.Mac mac = javax.crypto.Mac.getInstance("HmacSHA1");
		mac.init(new javax.crypto.spec.SecretKeySpec(accessSecret.getBytes("UTF-8"), "HmacSHA1"));
		byte[] signData = mac.doFinal(stringToSign.getBytes("UTF-8"));
		return new sun.misc.BASE64Encoder().encode(signData);
	}

    /**
     * EMA短信发送
     *
	 * @param nickname
	 * @param phone 手机号码
	 * @param smscode 验证码
	 * @param smsTemplayes
	 * @return
     * @throws UnsupportedEncodingException
     */
	public static Map<String,Object> sendEMASms(String nickname, String phone, String smscode, String smsTemplayes) throws UnsupportedEncodingException {

		Map<String,Object> resutlMap=new HashMap<>(4);
		String signName=nickname==null|| nickname.length()==0?SING_NAME:nickname;

		//短信路径
		String url="http://211.140.23.254:9885/c123/sendsms";
		//发送的参数
		String param="";
		//拼接用户账号
		param+="uid="+APP_ID;
		//拼接密码
		param+="&pwd="+APP_KEY;
		//拼接手机号码
		param+="&mobile="+phone;
		//拼接内容,1,先拼接签名
		param+="&content=";
		//组成内容,替换模板中的验证码
		smsTemplayes="【"+signName+"】"+smsTemplayes;
		smsTemplayes=smsTemplayes.replace("{smsCode}",smscode);
		smsTemplayes= URLEncoder.encode(smsTemplayes,"GBK");
		param+=smsTemplayes;
		String state = HttpClientUtil.doPost(url,param);
		if(state.isEmpty()){
			resutlMap.put("success",false);
			resutlMap.put("message", "调用接口失败！");
		}else {
			if(state.equals("100")){
				resutlMap.put("success", true);
				resutlMap.put("message", "短信发送成功，请注意查收！");
			}else {
				resutlMap.put("success", false);
				resutlMap.put("message", "短信发送失败!");
				String message=getEMASmsStateMessage(state);
				logger.info(state+"------"+message);
			}
		}
		System.out.println(resutlMap);
		return resutlMap;
	}


    public static void main(String[] args) throws UnsupportedEncodingException{
        //sendEMASms("13357705236","1993",SmsType.LOGIN_INFO.getValue());
    }
        /**
         * EMA短信返回状态码对应状态
         * @return
         */
	public static String getEMASmsStateMessage(String stateCode){
		switch (stateCode){
			case "101":
				return "验证失败";
			case "102":
				return "短信不足";
			case "103":
				return "操作失败";
			case "104":
				return "非法字符";
			case "105":
				return "内容过多";
			case "106":
				return "号码过多";
			case "107":
				return "频率过快";
			case "108":
				return "内容用了UTF-8，不支持，改成GBK即可";
			case "109":
				return "账号冻结";
			case "110":
				return "禁止频繁单条发送";
			case "111":
				return "系统暂定发送";
			case "112":
				return "子号不正确";
			case "120":
				return "验证码炸弹或签名未报备或请求符号错误";

		}
		return "未知错误";
	}
}
